package com.janko.springbootbase.controller;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Bookmark;
import org.apache.poi.hwpf.usermodel.Bookmarks;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.w3c.dom.Node;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName POIController
 * @Description TODO:
 * @Author janko
 * @Date 2020/12/2 18:08
 */
public class POIController {

    public static void main(String[] args)  {
        try {

            /** fixme poi中docx格式的文件要用XWPFDocument处理，doc格式的用HWPFDocument处理 */

            FileInputStream is = new FileInputStream("d:/template书签.docx");
            XWPFDocument doc = new XWPFDocument(is);

            InputStream isHWPF = new FileInputStream("d:/template书签.doc");
            HWPFDocument docHWPF = new HWPFDocument(isHWPF);
            printInfo(docHWPF.getBookmarks());

            Map<String,String> dataMap = new HashMap<>();
            dataMap.put("AB","ddddd");
            refreshBooks(doc,dataMap);

            doc.write(new FileOutputStream("d:/test012.docx"));
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 输出书签信息
     * @param bookmarks
     */
    private static  void printInfo(Bookmarks bookmarks) {
        int count = bookmarks.getBookmarksCount();
        System.out.println("书签数量：" + count);
        Bookmark bookmark;
        for (int i=0; i<count; i++) {
            bookmark = bookmarks.getBookmark(i);
            System.out.println("书签" + (i+1) + "的名称是：" + bookmark.getName());
            System.out.println("开始位置：" + bookmark.getStart());
            System.out.println("结束位置：" + bookmark.getEnd());
        }
    }

    public static void refreshBooks(XWPFDocument doc, Map<String, String> dataMap) {
        List<XWPFParagraph> paragraphs = doc.getParagraphs();
        for (XWPFParagraph xwpfParagraph : paragraphs) {
            CTP ctp = xwpfParagraph.getCTP();


            for (int dwI = 0; dwI < ctp.sizeOfBookmarkStartArray(); dwI++) {
                CTBookmark bookmark = ctp.getBookmarkStartArray(dwI);

                String data = dataMap.get(bookmark.getName());
                if (data != null) {
                    XWPFRun run = xwpfParagraph.createRun();
                    run.setText(data);

                    Node ctrNode=run.getCTR().getDomNode();
                    Node firstNode = bookmark.getDomNode();
                    Node nextNode = firstNode.getNextSibling();
                    while (nextNode != null) {
                        String nodeName = nextNode.getNodeName();
                        if (nodeName.equals("书签名字")) {
                            break;
                        }
                        Node delNode = nextNode;
                        nextNode = nextNode.getNextSibling();

                        ctp.getDomNode().removeChild(delNode);
                    }

                    if (nextNode == null) {
                        ctp.getDomNode().insertBefore(ctrNode, firstNode);
                    } else {
                        ctp.getDomNode().insertBefore(ctrNode, nextNode);
                    }
                }
            }
        }
    }

}
